#!/usr/bin/env ruby
#
def usage
<<-USAGE

Notice:
In the install_server.tar.gz template, following lines of Installr.conf should be applied.
-----------------
agent_port = ####
log_base_dir=/home/ideployer/installr_server_##/logs
data_base_dir=/home/ideployer/installr_server_##/data
-----------------

USAGE
end

if ARGV.length != 5
  puts "usage: #{$0} <agent count> <private_key.pem> <stress_server_IP> <stress_server_user> <start_port_number> <allow_server_IP>"
  puts "preparation: (server) installr_server.tar.gz, (client) private_key.pem"
  puts usage
  exit(-1)
end

puts "repeating #{ARGV[0]} times..."

puts "too many count" if ARGV[0].to_i > 100

1.upto(ARGV[0].to_i) do
  |idx|
  `tar xvpfz installr_server.tar.gz --transform 's/installr_server/installr_server_#{idx}/'`
  conf_file = "./installr_server_#{idx}/conf/Installr.conf"
  text = File.read(conf_file)
  replace_port=text.gsub!(/####/, "#{idx+ARGV[4].to_i-1}")
  replace_dir=replace_port.gsub!(/##/, "#{idx}")
  File.open(conf_file, "w") { |file| file.puts replace_dir }
  allow_file = "./installr_server_#{idx}/conf/hosts.allow"
  text = File.read(allow_file)
  File.open(allow_file, "w") do
    |file|
    file.puts text
    file.puts "#{ARGV[5]}"
  end  
end

File.open("startup_all.sh", "w") do
  |file|
  file.puts "#!/bin/sh"
  1.upto(ARGV[0].to_i) { |idx| file.puts "./installr_server_#{idx}/bin/InstallrAgent start" }
end

File.open("status_all.sh", "w") do
  |file|
  file.puts "#!/bin/sh"
  1.upto(ARGV[0].to_i) { |idx| file.puts "./installr_server_#{idx}/bin/InstallrAgent status" }
end

File.open("shutdown_all.sh", "w") do
  |file|
  file.puts "#!/bin/sh"
  1.upto(ARGV[0].to_i) { |idx| file.puts "./installr_server_#{idx}/bin/InstallrAgent stop" }
end

File.open("test_all.sh", "w") do
  |file|
  file.puts "./Installr create group stress_grp 'Stress group'"
  1.upto(ARGV[0].to_i) do
    |idx|
    file.puts "./Installr create agent stress_#{idx} #{ARGV[2]} --user #{ARGV[3]} -user --auth-file #{ARGV[1]} --passphrase sta --remote-port #{idx+ARGV[4].to_i-1} --remote-upload-path /tmp/Installr_#{idx}"
    file.puts "./Installr add agent stress_#{idx} to group stress_grp"
  end
  file.puts "./Installr list agents from group stress_grp"
  file.puts "./Installr deploy hello hello.war to group stress_grp"
  file.puts "./Installr history hello from group stress_grp"
  file.puts "./Installr undeploy hello from group stress_grp"
  file.puts "./Installr delete group stress_grp"
  1.upto(ARGV[0].to_i) do
    |idx|
    file.puts "./Installr delete agent stress_#{idx}"
  end
end

puts "Server prepation:"
puts "After executing this script, please issue the following command:"
puts "$ ruby -e \'1.upto(#{ARGV[0]}) { |idx| Dir.mkdir(\"/tmp/Installr_\#{idx}\") }\'"
puts "$ sh startup_all.sh"
puts "$ sh status_all.sh"
